import axios from 'axios';
import {ElMessage} from "element-plus";
export class Interceptors {
  public instance: any

  constructor() {
    this.instance = axios.create({
      baseURL: '/test-api', // api base_url
      timeout: 1000 * 300})
    this.initInterceptors()
  }

  public getInterceptors() {
    return this.instance
  }

  public initInterceptors() {
    // this.instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'
    /**
     * 请求拦截器
     * 每次请求前，如果存在token则在请求头中携带token
     */
    this.instance.interceptors.request.use(
      (config: any) => {
        if (!config.headers.Authorization) {
          const token = localStorage.getItem('ss_token');
          if (token) {
            config.headers.Authorization = token;
          } else {
            // @ts-ignore
            delete config.headers.Authorization
          }
        }
        return config;
      },
      (error: any) => {
      }
    );

    // 响应拦截器
    this.instance.interceptors.response.use(
      // 请求成功
      (res: any) => {
        if(res.data.code === 200){
          return Promise.resolve(res.data);
        } else if (res.data.code === 500) {
          ElMessage.error(res.data?.msg);
          return Promise.reject(res.data?.msg)
        } else {
          return Promise.resolve(res);
        }
      },
      // 请求失败
      (error: { response: any; }) => {
        const { response } = error;
        if (response) {
          // 请求已发出，但是不在2xx的范围
          this.errorHandle(response);
          return Promise.reject(response.data);
        } else {
          ElMessage.warning('网络连接异常,请稍后再试!');
          // 抛出报错信息，在页面里需要接收
          return Promise.reject(error);
        }
      });
  }

  private errorHandle(res: any) {
    console.error('错误接口：' + res.data.path)
    // 状态码判断
    switch (res.status) {
      case 401:
        ElMessage.warning(res.data.msg);
        break;
      case 403:
        break;
      case 404:
        ElMessage.error('请求的资源不存在');
        break;
      default:
        ElMessage.warning('连接错误');
    }
  }
}
